<template>
	<div class="zzh-upload">
		<span class="zzh-badge zzh-badge-out" v-if="imgUrl!=''&&showType=='oneself'" :data-src="imgUrl" @tap="delfile">X</span>
		<!-- <div class="zzh-upload-item" v-if="imgUrl==''||showType!='oneself'" @click.capture.stop="addfile"><slot></slot></div> -->
		<div class="zzh-upload-item" v-if="imgUrl==''||showType!='oneself'" @tap.stop="addfile"><slot></slot></div>
		<img class="zzh-upload-item" v-if="imgUrl!=''&&showType=='oneself'" :src="imgUrl" ref="zzhimg" :data-src="imgUrl" @tap.stop="previewImage"/>
	</div>
</template>

<script>
	export default {
		data(){
			return {
				imgArray:[],// 图片已上传 显示的数组
				imgUrl:'',//自身显示时的图片地址
				tempFiles:[],//选择的图片数组
				imgNumber: 0 // 统计img总数 防止重复
			}
		},
		props: {
			//最多可以选择的图片张数，默认1
			count:{
				type:Number,
				default: 1
			},
			//original 原图，compressed 压缩图，默认二者都有
			sizeType:{
				type:Array,
				default: function(){
					return ['compressed']
				}
			},
			//album 从相册选图，camera 使用相机，默认二者都有
			sourceType:{
				type:Array,
				default: function(){
					return ['album','camera']
				}
			},
			//显示类型（oneself组件内的img显示）
			showType:{
				type:String,
				default: 'oneself'
			},
			//是否自动上传
			autoUp:{
				type:Boolean,
				default: true
			},
			//上传图片接口
			uploadUrl:{
				type:String,
				default: ''
			},
			//删除图片接口
			deleteUrl:{
				type:String,
				default: ''
			},
			//图片上传大小限制
			imgMaxSize:{
				type:Number,
				default: 1024 * 1024 * 10
			},
			//矢代对象名称
			imgname:{
				type:String,
				default: 'imgname'
			},
			//是否可重复
			repeatable:{
				type:Boolean,
				default: false
			}
		},
		created(){
			const that = this;
			that.$emit("getfile",that.imgArray,that.imgname);
		},
		methods:{
			/**
			 * 得到一个图片id
			 */
			getUuid(){
				return "img-" + new Date().getTime() + "-" + this.imgNumber++;
			},
			
			/**
			 * 当自身显示是右上角删除按钮点击事件
			 */
			delfile(e){
				const that = this;
				console.log("e.target.dataset.src",e.currentTarget.dataset.src);
				if(that.deleteUrl){
					uni.showLoading();
					uni.request({
						url: that.deleteUrl,
						data: {url: e.currentTarget.dataset.src},
						method: 'GET',
						header: {
							'Content-Type': 'application/json;charset=utf-8',
						},
						success: function (res) {
							that.imgUrl = '';
							that.imgNumber--;
							that.imgArray.splice(that.imgArray.length-1,1);
							that.$emit("getfile",that.imgArray,that.imgname);
						},
						fail: function (err) {
							console.log('文件删除错误',err);
						},
						complete: function () {
							uni.hideLoading();
						},
					})
				}
			},
			
			/**
			 * 图片选择器
			 */
			addfile(){
				console.log("选择图片")
				const that = this;
				if(that.repeatable){
					that.imgArray=[];
				}
				let count = that.count-that.imgArray.length;
				uni.chooseImage({
					count: count,
					sizeType: that.sizeType,
					sourceType: that.sourceType,
					success: function (res) {
						that.tempFiles=res.tempFiles;
						that.handleChange();
					}
				});
			},
			
			/**
			 * 图片上传完成后的回调
			 */
			handleUploadEnd(data){
				const that = this;
				// 更改状态
				that.imgArray.map((item)=>{
					if(item.id===data.id){
						item.imgUrl=data.imgUrl;
						item.status=data.status;
					}
					return item;
				})
				// 上传下一个
				const nextUpload = that.uploadGen.next();
				if(!nextUpload.done){
					nextUpload.value.map((item)=>{
						that.uploadImg(item);
					});
				}else{
					uni.hideLoading();
					that.$emit("getfile",that.imgArray,that.imgname);
				}
			},
			
			/**
			 * 图片选择完成后的回调
			 */
			handleChange(){
				const that = this;
				const imgArray = that.imgArray;
				const uploadedImgArray = []; // 真正在页面显示的图片数组
				const uploadQueue = []; // 图片上传队列 这个队列是在图片选中到上传之间使用的 上传完成则清除
				
				// 检查文件个数 页面显示的图片个数不能超过限制
				if(imgArray.length + that.tempFiles.length > that.count){
					uni.showToast({title:'文件数量超出最大值',icon: 'none'});
					return;
				}
				
				let imgPass = {typeError: false, sizeError: false};
				// 循环遍历检查图片 类型、尺寸检查
				that.tempFiles.map((item)=>{
					// 图片尺寸检查
					if(item.size > that.imgMaxSize){
						imgPass.sizeError = true;
					}
					// 为图片加上位移id
					const uuid = that.getUuid();
					// 上传队列加入该数据
					uploadQueue.push({id: uuid, path: item.path, size: item.size,imgUrl:'',status: 1});
					// 页面显示加入数据
					uploadedImgArray.push({ // 显示在页面的数据的标准格式
						id: uuid, // 图片唯一id
						path: item.path, // 上传前的本地路径
						size: item.size,
						imgUrl: '', // 图片真实路径 后端返回的
						status: 1 // status表示这张图片的状态 1：上传中，2上传成功，3：上传失败
					});
				});
				
				// 有错误跳出
				if(imgPass.sizeError){
					uni.showToast({title:'文件大小超过限制',icon: 'none'});
					return;
				}
				
				// 页面先显示一共上传图片个数
				that.imgArray = imgArray.concat(uploadedImgArray);
				
				if(that.autoUp && !!that.uploadUrl){
					// 通过该函数获取每次要上传的数组
					that.uploadGen = that.uploadGenerator(uploadQueue);
					// 第一次要上传的数量
					const firstUpload = this.uploadGen.next();
					// 真正开始上传流程
					firstUpload.value.map((item)=>{
						that.uploadImg(item);
					});
				}else{
					that.$emit("getfile",that.imgArray,that.imgname);
				}
			},
			
			/**
			 * 生成上传队列
			 */
			*uploadGenerator (uploadQueue) {
				// 最多只有三个请求在上传
				const maxUploadSize = 3;
				if(uploadQueue.length > maxUploadSize){
					const result = [];
					for(let i = 0; i < uploadQueue.length; i++){
						// 第一次return maxUploadSize数量的图片
						if(i < maxUploadSize){
							result.push(uploadQueue[i]);
							if(i === maxUploadSize - 1){
								yield result;
							}
						} else {
							yield [uploadQueue[i]];
						}
					}
				} else {
					yield uploadQueue.map((item)=>(item));
				}
			},
			
			/**
			 * 图片上传函数
			 */
			uploadImg (data) {
				const that = this;
				uni.showLoading();
				let uploadTask = uni.uploadFile({
					url: that.uploadUrl,
					filePath: data.path,
					name: 'file',
					success: (res) => {
						console.log("=========res",res);
						if(res.statusCode==200 && JSON.parse(res.data)["code"] == 0){
							data.imgUrl=JSON.parse(res.data)["url"];
							that.imgUrl=JSON.parse(res.data)["url"];
							data.status=2;
							that.handleUploadEnd(data);
						}else{
							data.status=3;
							that.handleUploadEnd(data);
						}
					},
					fail: (res) => {
						data.status=3;
						that.handleUploadEnd(data);
					},
					complete: function () {
						/* if(data.id==that.imgArray[that.imgArray.length-1].id){
							uni.hideLoading();
							that.$emit("getfile",that.imgArray,that.imgname);
						} */
					},
				});
				uploadTask.onProgressUpdate((res) => {
					console.log('上传个数' , data.id.split("-")[2]);
					if(res.progress==50){
						console.log('上传进度:50');
					}
				});
			},
			
			/**
			 * 图片预览
			 */
			previewImage(e){
				let current = e.currentTarget.dataset.src;
				let urls = [current];
				uni.previewImage({
					current: current,
					urls: urls
				}) 
			}
		}
	  }
</script>

<style scoped>
	.zzh-upload{
		position: relative;
	}
	.zzh-upload .zzh-upload-item{
		height:100%;
		width:100%;
	}
	.zzh-upload .zzh-badge{
		font-size: 14px;
		line-height: 1.4;
		color: #fff;
		background: red;
		border-radius: 50%;
		padding: 1px 5px;
		position: absolute;
		right: 0px;
	}
	.zzh-upload .zzh-badge-out{
		right: -9px;
		top: -9px;
	}
</style>
